<template>
  <VChart
    class="chart"
    :option="options"
    :autoresize="true"
    @chart-ready="handleChartReady"
  />
</template>

<script setup>
import { ref, watch, onBeforeUnmount,onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 按需注册必要组件
use([
  CanvasRenderer,
  LineChart,
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
])

const props = defineProps({
  chartData: {
    type: Object,
    required: true,
    default: () => ({
      dates: [],
      values: []
    })
  }
})

// 图表实例引用
const chartInstance = ref(null)
const handleChartReady = (instance) => {
  chartInstance.value = instance
}

// 响应式配置项
const options = ref({
  title: {
    text: '访问量趋势',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: props.chartData.dates,
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '访问量',
      type: 'line',
      data: props.chartData.values,
      smooth: true,
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(64, 158, 255, 0.6)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.01)' }
          ]
        }
      },
      itemStyle: {
        color: '#409EFF'
      }
    }
  ],
  grid: {
    containLabel: true,
    left: '3%',
    right: '3%',
    bottom: '15%'
  }
})

// 监听数据变化
watch(
  () => props.chartData,
  (newVal) => {
    options.value = {
      ...options.value,
      xAxis: { data: newVal.dates },
      series: [{ data: newVal.values }]
    }
  },
  { deep: true }
)

// 自动resize处理
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.chart {
  width: 100%;
  height: 400px;
}
</style>